// 编译
class Compiler {
  constructor(vm) {
    this.el = vm.$el
    this.vm = vm

    this.compile(this.el)
  }

  compile(el) {
    let childNodes = el.childNodes;
    // console.log(childNodes);
    Array.from(childNodes).forEach(node => {
      // 处理文本节点
      if (this.isTextNode(node)) {
        this.compileText(node)
      } else if (this.isElementNode(node)) {
        // 处理元素节点
        this.compileElement(node)
      }

      // 判断node节点，是否有子节点，如果有字节蒂娜，要递归调用compile
      if (node.childNodes && node.childNodes.length) {
        this.compile(node)
      }
    })
  }

  // 编译文本节点，处理差值表达式
  compileText(node) {
    // console.dir(node)
    // {{ msg }}
    let reg = /\{\{(.+?)\}\}/
    let value = node.textContent
    if (reg.test(value)) {
      let key = RegExp.$1.trim()
      node.textContent = value.replace(reg, this.vm[key])
    }
  }

  // 编译元素节点，处理指令
  compileElement(node) {
    // 遍历所有的属性节点
    Array.from(node.attributes).forEach(attribute => {
      // 判断是否是指令
      let attributeName = attribute.name
      let targetAttribute = attribute.value
      if (this.isDirective(attributeName)) {
        // v-text --> text
        attributeName = attributeName.substr(2)
        
        // 针对 v-on:click 处理
        if (attributeName.includes(':')) {
          let eventType = attributeName.slice(attributeName.indexOf(':') + 1)
          this.eventUpdater(node, this.vm.$options.methods[targetAttribute].bind(this.vm), eventType)
        }
        let key = attribute.value
        this.update(node, key, attributeName)
      }
    })
  }

  update(node, key, attributeName) {
    let updateFn = this[attributeName + 'Updater']
    updateFn && updateFn.call(this, node, this.vm[key], key)
  }

  // v-on 指令
  eventUpdater(node, value, key) {
    node.addEventListener(key, value, false)
  }

  // v-text 指令
  textUpdater(node, value, key) {
    node.textContent = value;

    new Watcher(this.vm, key, (newValue) => {
      node.textContent = newValue
    })
  }

  // v-model 指令
  modelUpdater(node, value, key) {
    node.value = value

    new Watcher(this.vm, key, (newValue) => {
      node.value = newValue
    })
  }

  // v-html 指令
  htmlUpdater(node, value, key) {
    node.innerHTML = value;

    new Watcher(this.vm, key, (newValue) => {
      node.innerHTML = newValue
    })
  }

  // 判断元素属性是否是指令
  isDirective(attributeName) {
    return attributeName.startsWith('v-')
  }

  // 判断节点是否是文本节点
  isTextNode(node) {
    return node.nodeType === 3
  }

  // 判断节点是否是元素节点
  isElementNode(node) {
    return node.nodeType === 1
  }

}